package com.wsc.wisdomchina.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.mob.MobApplication;
import com.samton.mainSDK.MainSDK;
import com.samton.utils.PreferenceUtil;
import com.tencent.android.tpush.XGPushManager;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchina.BuildConfig;
import com.wsc.wisdomchina.Tools.DeviceUuidFactory;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.ai.db.DbManager;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.httpUtils.HttpHeadParams;
import com.wsc.wisdomchina.javaBean.ApplyTitleListBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.wsc.wisdomchina.BuildConfig;
import com.wsc.wisdomchina.javaBean.ApplyTitleListBean;
import com.wsc.wisdomchina.javaBean.StreetInfoListBean;
import com.wsc.wisdomchina.presenter.ContributorPresenter;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * @author jaily.zhang
 * @version V1.3.1
 * @Description 全局变量
 * @date 2014-9-3 下午1:55:31
 */
public class MyApplication extends MobApplication implements ContributorView {
    private String version;// 软件版本号
    private String Uuid;// 手机物理唯一标识
    private String osType;// 手机操作系统
//    private String imei;// imei 号码
    private String mac;// mac 地址
    private String market;// 应用市场编号
    private final String ENTERPRISE_FLAG="ENTERPRISE_FLAG";
    private ApplicationInfo appInfo;
    private String wscSecretKey;
    private String wscAccessKey;
    private String informationFragmentSelected;// 选中的资讯页面Fragment标记
    private List<String> ModuleId;
    private List<String> ModuleName;
    private List<String> TitleListName;
    private List<Integer> TitleListType;
    private List<ApplyTitleListBean> CenterApplyList;
    public List<Activity> activities;
    private String sourceIntoLoginRegisterActivity;
    private HashMap<String, String> questionMap = new HashMap<>();
    private String locationCity;//高德地图获取到的定位城市
    private String locationDistrict;//高德地图获取到的定位区县
    private String locationAddress="";//定位的具体位置
    private double latitude;//维度
    private double longitude;//精度
    private int selectShouliCenterIndex=0;
    private String IP;
    private boolean isRefreshPartyChat;//是否刷新交流园地列表
    private String jPushRegisterId;

    // 用户的唯一标识开发者自行设计
    private static String userId = "lhg测试";
    private static MainSDK mainSdk = null;
    /**
     * 共享存储对象
     */
    public static PreferenceUtil preferenceUtil = null;
    private String cidNumber;
    private StreetInfoListBean streetInfoListBean;
    private ContributorPresenter contributorPresenter;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        MobclickAgent.openActivityDurationTrack(false);
        // 得到应用市场渠道编号
        if (market == null) {
            market = getAppInfo().metaData.getString("UMENG_CHANNEL");
            if (market == null)
                market = Integer.toString(getAppInfo().metaData.getInt("UMENG_CHANNEL"));
        }
        contributorPresenter=new ContributorPresenter(this,this);
        // 获取version
        version = BuildConfig.VERSION_NAME;
        // 获取Uuid
        Uuid = new DeviceUuidFactory(getApplicationContext()).getDeviceUuid();
//        // 获取OsType
        osType = getOsVersion();
        // 获取到imei
//        imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
        // 获取MAC地址
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        mac = info.getMacAddress();
        wscSecretKey = getAppInfo().metaData.getString("WSC_SECRETKEY");
        wscAccessKey = getAppInfo().metaData.getString("WSC_ACCESSKEY");
        activities = new ArrayList<>();

        // 初始化HttpHeadParams 字段
        initHttpHeadInstance();
		jPushRegisterId= JPushInterface.getRegistrationID(getApplicationContext());
        Log.i("123456789","jPushRegisterId:" + jPushRegisterId);


        mainSdk = new MainSDK(this);
        mainSdk.initSDK(this);
        String eId = Tools.getSharedPreferencesStrings(Constant.EnterpriseId,"",this);
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", this);
        if (locationString.length() > 0) {
            streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber=streetInfoListBean.getId();
        }
        if(TextUtils.isEmpty(eId)){
            contributorPresenter.getEnterpriseId(cidNumber,ENTERPRISE_FLAG);
        }else{
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            String apiKey ="435ce620c98449e49f0828a25de9f013";
            String apiSecret = "dfba912a2f6f49628bfac558eba5c515";
            String sourceType = "4";
            mainSdk.init(imei,apiKey,"com.samton",apiSecret, eId, sourceType);
        }

        //线上
//        mainSdk.init(userId, "D9172EDC3FF3425490E3828FC3DBA469", "com.samton");
        // 线上测试
       // mainSdk.init(userId, "A31828C1BD80449E8814CB2CD02423D4", "didi");
        // 测试环境  新的测试  iben.com	8D0C992DD7194859BA6A29148BE52BA3
        //mainSdk.init(userId, "8D0C992DD7194859BA6A29148BE52BA3", "iben.com");
        // 测试  com.samton	C08923A07AE74F03A8294FA30B0BEFB0
        //mainSdk.init(userId, "C08923A07AE74F03A8294FA30B0BEFB0", "com.samton");
        //信鸽推送注册
        XGPushManager.registerPush(this);
        // 初始化 本地存储数据库
        DbManager.init(this);
        // 初始化共享存储工具
        preferenceUtil = new PreferenceUtil(this);
    }
    public static String getUserId() {
        return userId;
    }

    public static MainSDK getMainSdk() {
        return mainSdk;
    }
    /**
     * @return
     * @throws Exception
     * @Description 获取手机版本号
     * @author jaily.zhang
     */
    private String getOsVersion() {
        // 获取packagemanager的实例
        return "Android " + android.os.Build.VERSION.RELEASE + "," + android.os.Build.MANUFACTURER + "," + android.os.Build.MODEL;
    }

    public String getWscSecretKey() {
        return wscSecretKey;
    }

    public String getWscAccessKey() {
        return wscAccessKey;
    }

    public String getInformationFragmentSelected() {
        return informationFragmentSelected;
    }

    public void setInformationFragmentSelected(String informationFragmentSelected) {
        this.informationFragmentSelected = informationFragmentSelected;
    }
 public static boolean getSPValue(){
     if(preferenceUtil == null){
         return false;
     }
     return preferenceUtil.getBoolean("isGrade",false);

 }
    public ApplicationInfo getAppInfo() {
        if (appInfo == null) {
            try {
                appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);

            } catch (NameNotFoundException e) {

            }
        }
        return appInfo;
    }

    public List<String> getModuleId() {
        return ModuleId;
    }

    public void setModuleId(List<String> eightModuleId) {
        this.ModuleId = eightModuleId;
    }

    public List<String> getModuleName() {
        return ModuleName;
    }

    public void setModuleName(List<String> eightModuleName) {
        this.ModuleName = eightModuleName;
    }

    /**
     * 初始化 httpHeadInsatnce
     */
    private void initHttpHeadInstance() {
        HttpHeadParams.getInstance().setAccessKey(wscAccessKey);
        HttpHeadParams.getInstance().setSecretKey(wscSecretKey);
        HttpHeadParams.getInstance().setUuid(Uuid);
        HttpHeadParams.getInstance().setVersion(version);
        HttpHeadParams.getInstance().setOs(osType);
        HttpHeadParams.getInstance().setMarket(market);
        HttpHeadParams.getInstance().setMac(mac);
//        HttpHeadParams.getInstance().setImei(imei);
    }

    public String getSourceIntoLoginRegisterActivity() {
        return sourceIntoLoginRegisterActivity;
    }

    public void setSourceIntoLoginRegisterActivity(String sourceIntoLoginRegisterActivity) {
        this.sourceIntoLoginRegisterActivity = sourceIntoLoginRegisterActivity;
    }

    public HashMap<String, String> getQuestionMap() {
        return questionMap;
    }

    public void setQuestionMap(HashMap<String, String> questionMap) {
        this.questionMap = questionMap;
    }

    public String getLocationCity() {
        return locationCity;
    }

    public void setLocationCity(String locationCity) {
        this.locationCity = locationCity;
    }

    public String getLocationDistrict() {
        return locationDistrict;
    }

    public void setLocationDistrict(String locationDistrict) {
        this.locationDistrict = locationDistrict;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public List<String> getTitleListName() {
        return TitleListName;
    }

    public void setTitleListName(List<String> titleListName) {
        TitleListName = titleListName;
    }

    public List<Integer> getTitleListType() {
        return TitleListType;
    }

    public void setTitleListType(List<Integer> titleListType) {
        TitleListType = titleListType;
    }

    public List<ApplyTitleListBean> getCenterApplyList() {
        return CenterApplyList;
    }

    public void setCenterApplyList(List<ApplyTitleListBean> centerApplyList) {
        CenterApplyList = centerApplyList;
    }

    public int getSelectShouliCenterIndex() {
        return selectShouliCenterIndex;
    }

    public void setSelectShouliCenterIndex(int selectShouliCenterIndex) {
        this.selectShouliCenterIndex = selectShouliCenterIndex;
    }

    public String getLocationAddress() {
        return locationAddress;
    }

    public void setLocationAddress(String locationAddress) {
        this.locationAddress = locationAddress;
    }

    public String getIP() {
        return IP;
    }

    public void setIP(String IP) {
        this.IP = IP;
    }

    public boolean isRefreshPartyChat() {
        return isRefreshPartyChat;
    }

    public void setRefreshPartyChat(boolean refreshPartyChat) {
        isRefreshPartyChat = refreshPartyChat;
    }

    public String getjPushRegisterId() {
        return jPushRegisterId;
    }

    public void setjPushRegisterId(String jPushRegisterId) {
        this.jPushRegisterId = jPushRegisterId;
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            if(ENTERPRISE_FLAG.equals(flag)){
                JSONObject json = new JSONObject(jsonString);
                String enterpriseid= json.optString("obj");
                Tools.setSharedPreferencesStrings(Constant.EnterpriseId,enterpriseid,this);
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                String imei = telephonyManager.getDeviceId();
                String apiKey ="435ce620c98449e49f0828a25de9f013";
                String apiSecret = "dfba912a2f6f49628bfac558eba5c515";
                String sourceType = "4";
                mainSdk.init(imei,apiKey,"com.samton",apiSecret, enterpriseid, sourceType);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onLoadContributorComplete(String flag) {

    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }
}